/**
 * 材质库管理器
 * 管理项目的材质库，包括创建、编辑、删除、重命名材质
 */

export class MaterialLibraryManager {
    constructor(projectId) {
        this.projectId = projectId;
        this.materials = [];
    }
    
    /**
     * 加载材质库
     */
    async loadMaterials(options = {}) {
        try {
            const cacheBuster = options.forceRefresh !== false ? `?_t=${Date.now()}` : '';
            const response = await fetch(`/api/projects/${this.projectId}/materials${cacheBuster}`);
            const result = await response.json();
            
            if (result.success) {
                this.materials = result.data || [];
                return this.materials;
            } else {
                console.warn('⚠️ 加载材质库失败:', result.error);
                return [];
            }
        } catch (error) {
            console.warn('⚠️ 加载材质库失败:', error);
            return [];
        }
    }
    
    /**
     * 创建新材质
     */
    async createMaterial(materialData) {
        try {
            // 验证displayName
            if (!materialData.displayName || materialData.displayName.trim() === '') {
                throw new Error('材质显示名称不能为空');
            }
            
            // 调用后端创建材质（后端会自动处理重复情况）
            const response = await fetch(`/api/projects/${this.projectId}/materials`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(materialData)
            });
            
            const result = await response.json();
            
            if (result.success) {
                // 如果材质已存在，existed 为 true；如果是新创建的，existed 为 false
                if (result.existed) {
                    console.log(`ℹ️ 材质 "${materialData.displayName}" 已存在，使用现有材质`);
                }
                
                await this.loadMaterials(); // 重新加载列表
                
                // 返回材质数据，包含 existed 标记
                return {
                    ...result.data,
                    existed: result.existed
                };
            } else {
                throw new Error(result.error || '创建失败');
            }
        } catch (error) {
            console.error('❌ 创建材质失败:', error);
            throw error;
        }
    }
    
    /**
     * 获取材质详情
     * ✅ 新架构：使用 displayName 作为参数
     */
    async getMaterial(displayName) {
        try {
            const encodedDisplayName = encodeURIComponent(displayName);
            const response = await fetch(`/api/projects/${this.projectId}/materials/${encodedDisplayName}`);
            const result = await response.json();
            
            if (result.success) {
                return result.data;
            } else {
                throw new Error(result.error || '获取失败');
            }
        } catch (error) {
            console.error('❌ 获取材质失败:', error);
            throw error;
        }
    }
    
    /**
     * 更新材质
     * ✅ 新架构：使用 displayName 作为参数
     */
    async updateMaterial(displayName, materialData) {
        try {
            const encodedDisplayName = encodeURIComponent(displayName);
            const response = await fetch(`/api/projects/${this.projectId}/materials/${encodedDisplayName}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(materialData)
            });
            
            const result = await response.json();
            
            if (result.success) {
                await this.loadMaterials(); // 重新加载列表
                return result.data;
            } else {
                throw new Error(result.error || '更新失败');
            }
        } catch (error) {
            console.error('❌ 更新材质失败:', error);
            throw error;
        }
    }
    
    /**
     * 删除材质
     * ✅ 新架构：使用 displayName 作为参数
     */
    async deleteMaterial(displayName) {
        try {
            const encodedDisplayName = encodeURIComponent(displayName);
            const response = await fetch(`/api/projects/${this.projectId}/materials/${encodedDisplayName}`, {
                method: 'DELETE'
            });
            
            const result = await response.json();
            
            if (result.success) {
                await this.loadMaterials(); // 重新加载列表
                return true;
            } else {
                // 创建错误对象，附加引用数据
                const error = new Error(result.error || '删除失败');
                if (result.usedByMeshes) {
                    error.usedByMeshes = result.usedByMeshes;
                }
                throw error;
            }
        } catch (error) {
            console.error('❌ 删除材质失败:', error);
            throw error;
        }
    }
    
    /**
     * 重命名材质
     * ✅ 新架构：使用 displayName 作为参数
     */
    async renameMaterial(oldDisplayName, newDisplayName) {
        try {
            // 验证新displayName
            if (!newDisplayName || newDisplayName.trim() === '') {
                throw new Error('材质显示名称不能为空');
            }
            
            // 检查新displayName是否重复
            if (this.materials.some(m => m.displayName === newDisplayName)) {
                throw new Error('材质名称已存在');
            }
            
            const encodedOldDisplayName = encodeURIComponent(oldDisplayName);
            const response = await fetch(`/api/projects/${this.projectId}/materials/${encodedOldDisplayName}/rename`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ newDisplayName })
            });
            
            const result = await response.json();
            
            if (result.success) {
                await this.loadMaterials(); // 重新加载列表
                return result.data;
            } else {
                throw new Error(result.error || '重命名失败');
            }
        } catch (error) {
            console.error('❌ 重命名材质失败:', error);
            throw error;
        }
    }
    
    /**
     * 应用材质到模型
     * ✅ 新架构：使用 materialName (displayName) 作为参数
     */
    async applyMaterialToModel(modelId, materialName) {
        try {
            const response = await fetch(`/api/projects/${this.projectId}/models/${modelId}/apply-material`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ materialName })
            });
            
            const result = await response.json();
            
            if (result.success) {
                return true;
            } else {
                throw new Error(result.error || '应用失败');
            }
        } catch (error) {
            console.error('❌ 应用材质到模型失败:', error);
            throw error;
        }
    }
    
    /**
     * 获取默认材质参数
     */
    static getDefaultMaterialParams() {
        return {
            color: '#ffffff',
            metalness: 0.5,
            roughness: 0.5,
            emissive: '#000000',
            emissiveIntensity: 0,
            opacity: 1.0,
            aoIntensity: 1.0,
            bumpScale: 0.0,
            doubleSided: false,
            map: null,
            normalMap: null,
            bumpMap: null,
            aoMap: null,
            roughnessMap: null,
            metalnessMap: null
        };
    }
}

// 导出单例
let materialLibraryManagerInstance = null;

export function getMaterialLibraryManager(projectId) {
    if (!materialLibraryManagerInstance || materialLibraryManagerInstance.projectId !== projectId) {
        materialLibraryManagerInstance = new MaterialLibraryManager(projectId);
    }
    return materialLibraryManagerInstance;
}

/**
 * 卸载材质库管理器
 */
export function unloadMaterialLibraryManager() {
    if (materialLibraryManagerInstance) {
        materialLibraryManagerInstance.materials = [];
        materialLibraryManagerInstance = null;
        window.materialLibraryManager = null;
    }
}

// 暴露到全局
window.getMaterialLibraryManager = getMaterialLibraryManager;
window.unloadMaterialLibraryManager = unloadMaterialLibraryManager;

